<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="角色名" prop="name">
        <el-col :span="14">
          <el-input v-model="form.name"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="remark" label-width="100px">
        <el-col :span="14">
          <el-input v-model="form.remark" type="textarea"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="菜单权限" prop="menu_ids" label-width="100px">
        <el-col :span="14">
          <el-tree
            ref="tree"
            :data="menus"
            :default-checked-keys="form.menu_ids"
            :props="{ children: 'children', label: 'title' }"
            node-key="id"
            show-checkbox
            accordion
            highlight-current
            @check-change="handleCheckChange"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="状态" label-width="120px">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getMenuTree } from "@/api/menu";
import { detailRole, addRole, editRole } from "@/api/role";

const defaultForm = {
  name: "",
  remark: "",
  status: 1,
  menu_ids: [],
};

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    this.getMenus();
  },
  created() {
    if (this.isEdit) {
      this.getRoleDetail(this.$route.params.id);
    }
  },
  data() {
    // 验证
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        this.$message({
          message: rule.field + "为必传项",
          type: "error",
        });
        callback(new Error(rule.field + "为必传项"));
      } else {
        callback();
      }
    };
    return {
      menus: [],
      form: Object.assign({}, defaultForm),
      rules: {
        name: [{ validator: validateRequire }],
      },
    };
  },
  methods: {
    // 菜单树
    getMenus() {
      getMenuTree().then((response) => {
        this.menus = response.data;
      });
    },
    // 获取角色详情
    getRoleDetail(id) {
      detailRole(id).then((response) => {
        this.form = response.data;
      });
    },
    // 监听选中的菜单id
    handleCheckChange(data, checked, indeterminate) {
      // 清空旧的菜单id
      this.form.menu_ids = [];
      let nodeData = this.$refs.tree.getCheckedNodes();
      nodeData.forEach((el) => {
        if (!el.children) {
          this.form.menu_ids.push(el.id);
        }
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          const data = Object.assign({}, this.form);
          // // 获取选中的菜单id
          // let nodeData = this.$refs.tree.getCheckedNodes();
          // nodeData.forEach(el => {
          //   if (!el.children) {
          //     this.form.menu_ids.push(el.id);
          //   }
          // })
          if (!this.isEdit) {
            // 新增角色
            addRole(data).then((response) => {
              this.loading = false;
              this.$notify({
                title: response.message,
                message: response.message,
                type: response.code == 1 ? "success" : "error",
                duration: 2000,
              });
              if (response.code == 1) {
                this.$router.push("/auth/role/list");
              }
            });
          } else {
            // 更新角色
            editRole(this.$route.params.id, data).then((response) => {
              this.loading = false;
              this.$notify({
                title: response.message,
                message: response.message,
                type: response.code == 1 ? "success" : "error",
                duration: 2000,
              });
              if (response.code == 1) {
                this.$router.push("/auth/role/list");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>